﻿using Common;
using FluentValidation.Results;
using HslCommunication.Core;
using PLC.Domain.Dto;
using PLC.Domain.Enum;
using PLC.Domain.Models;
using PLC.Domain.Service.IRepository;

namespace PLC.Domain.ScheduledTasks.Strategy.Write;

public abstract class BaseWrite
{
    private readonly IPLCRepository _plcRepository;

    protected BaseWrite(IPLCRepository plcRepository)
    {
        _plcRepository = plcRepository ?? throw new ArgumentNullException(nameof(plcRepository));
    }
    public abstract List<EnumWriteGroup> WriteGroups { get; protected set; }

    public abstract void Write(IReadWriteNet readWriteNet, PLCConfig plcConfig, DtoDataConfig dataConfig, int triggerResult);

    /// <summary>
    /// 基础的写入类型  值写入ok 和ng对应的值
    /// </summary>
    /// <param name="readWriteNet"></param>
    /// <param name="plcConfig"></param>
    /// <param name="dataConfig"></param>
    /// <param name="triggerResult"></param>
    /// <exception cref="Exception"></exception>
    protected void WriteBase(IReadWriteNet readWriteNet, PLCConfig plcConfig, DtoDataConfig dataConfig,
        int triggerResult)
    {
        if (triggerResult==0)
        {
            throw new Exception("回写的值不能为0");
        }
        // 要转成ok ng然后找到对应的回写值
        if (dataConfig.DataDescriptionList == null||dataConfig.DataDescriptionList.Count==0) 
        {
            // 如果没有配置回写值  那么就不回写
            return;
        }
        var item =  dataConfig.DataDescriptionList.FirstOrDefault(p=>p.Description==triggerResult.ToString());
        if (item == null)
        {
            return;
        }
        // 写入
        _plcRepository.WriteData(readWriteNet, dataConfig.Register, item.Value, (EnumDataType)dataConfig.DataType, (EnumDataEncoding)(dataConfig.Encoding ?? 0), plcConfig.DeviceConfig.Protocol.Value);
    }
}